﻿using System;
using System.ComponentModel;
using System.Net;
using System.Windows;
using System.Windows.Media;
using System.Windows.Navigation;
using CuteRibs.D3Armory.Models;
using CuteRibs.D3Armory.Resources;
using CuteRibs.D3Armory.ViewModels;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;

namespace CuteRibs.D3Armory.Views
{
	public partial class HeroPage : PageBase
	{
		private HeroPageViewModel myViewModel;

		public HeroPageViewModel MyViewModel
		{
			get
			{
				if (this.myViewModel == null)
				{
					this.myViewModel = (HeroPageViewModel)this.DataContext;
				}

				return this.myViewModel;
			}
		}

		public Realm Realm { get; set; }
		public string BattleTag { get; set; }
		public uint HeroId { get; set; }

		public HeroPage()
			: base()
		{
			InitializeComponent();

			this.Loaded += delegate
			{
				this.AppButtons[0].Text = AppRes.btnRefresh;
			};
		}

		private async void LoadData(bool refresh = false)
		{
			this.MyViewModel.ShowProgressBar = true;
			Hero hero = null;

			try
			{
				if (refresh)
				{
					hero = await App.GetHero(this.Realm, this.BattleTag, this.HeroId);
				}
				else
				{
					hero = await App.LoadHero(this.Realm.Region.ToString(), this.BattleTag, this.HeroId);
				}

				if (!string.IsNullOrEmpty(hero.ErrorCode))
				{
					App.ShowAlert(string.Format("{0}: {1}", hero.ErrorCode, hero.ErrorReason));
					this.MyViewModel.HeroViewModel = null;
				}
				else
				{
					this.MyViewModel.HeroViewModel = new HeroViewModel(hero, refresh);
				}
			}
			catch (Exception ex)
			{
				if (ex is WebException || ex is JsonReaderException)
				{
					App.ShowAlert(AppRes.MsgDataAccessError);
				}
				else
				{
					App.ShowError(new AppException(ex, this.Realm, this.BattleTag, this.HeroId));
				}
			}

			this.MyViewModel.ShowProgressBar = false;
		}

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			string region, battleTag, heroId;
			this.NavigationContext.QueryString.TryGetValue("Region", out region);
			this.NavigationContext.QueryString.TryGetValue("BattleTag", out battleTag);
			this.NavigationContext.QueryString.TryGetValue("Hero", out heroId);
			this.Realm = Realm.Parse(region);
			this.BattleTag = battleTag;
			this.HeroId = uint.Parse(heroId);
			this.LoadData();
		}

		protected override void OnBackKeyPress(CancelEventArgs e)
		{
			if (this.popup.IsOpen)
			{
				this.popup.IsOpen = false;
				e.Cancel = true;
			}
		}

		private async void Item_Tap(object sender, System.Windows.Input.GestureEventArgs e)
		{
			var control = sender as FrameworkElement;
			var viewModel = control.DataContext as ItemViewModel;

			if (viewModel == null)
			{
				return;
			}

			this.MyViewModel.ShowProgressBar = true;
			this.MyViewModel.TooltipBorderColor = viewModel.BorderBrush;
			string html = null;

			try
			{
				html = await App.LoadItemTooltip(viewModel.Item.TooltipParams);
			}
			catch (Exception ex)
			{
				if (ex is WebException)
				{
					App.ShowAlert(AppRes.MsgDataAccessError);
				}
				else
				{
					App.ShowError(new AppException(ex, viewModel.Item.TooltipParams));
				}
			}

			if (string.IsNullOrWhiteSpace(html))
			{
				this.MyViewModel.ShowProgressBar = false;
			}
			else
			{
				this.wbTooltip.NavigateToString(html);
			}
		}

		private async void Skill_Tap(object sender, System.Windows.Input.GestureEventArgs e)
		{
			var control = sender as FrameworkElement;
			var viewModel = control.DataContext as SkillViewModel;

			if (viewModel == null || viewModel.SkillSet == null || viewModel.SkillSet.Skill == null)
			{
				return;
			}

			this.MyViewModel.ShowProgressBar = true;
			this.MyViewModel.TooltipBorderColor = new SolidColorBrush(Helper.ParseColor(0x322A20));
			string html = null;

			try
			{
				html = await App.LoadSkillTooltip(viewModel.TooltipParams, viewModel.RuneType);
			}
			catch (Exception ex)
			{
				if (ex is WebException)
				{
					App.ShowAlert(AppRes.MsgDataAccessError);
				}
				else
				{
					App.ShowError(new AppException(ex, viewModel.TooltipParams));
				}
			}

			if (string.IsNullOrWhiteSpace(html))
			{
				this.MyViewModel.ShowProgressBar = false;
			}
			else
			{
				this.Dispatcher.BeginInvoke(delegate
				{
					this.wbTooltip.NavigateToString(html);
				});
			}
		}

		private void WebBrowser_ScriptNotify(object sender, NotifyEventArgs e)
		{
			var browser = sender as WebBrowser;
			browser.Height = double.Parse(e.Value) * 1.3446d;
			this.popup.IsOpen = true;
			this.MyViewModel.ShowProgressBar = false;
		}

		private void Popup_Tap(object sender, System.Windows.Input.GestureEventArgs e)
		{
			this.Dispatcher.BeginInvoke(delegate
			{
				this.popup.IsOpen = false;
			});
		}

		private void btnRefresh_Click(object sender, EventArgs e)
		{
			this.LoadData(true);
		}
	}
}